<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
<!--      <el-form-item label="站点" prop="siteId">-->
<!--        <el-input-->
<!--          v-model="queryParams.siteId"-->
<!--          placeholder="请输入站点"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="套餐" prop="itemId">-->
<!--        <el-input-->
<!--          v-model="queryParams.itemId"-->
<!--          placeholder="请输入套餐"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item label="" prop="type">
        <el-radio-group v-model="queryParams.type" @change="getList">
          <el-radio-button :label="''">全部</el-radio-button>
          <el-radio-button label="vip">VIP套餐</el-radio-button>
          <el-radio-button label="reseller">分销商套餐</el-radio-button>
          <el-radio-button label="usable">剧场积分套餐</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
<!--      <el-form-item label="兑换码" prop="pwd">-->
<!--        <el-input-->
<!--          v-model="queryParams.pwd"-->
<!--          placeholder="请输入兑换码"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="有效期" prop="usetime">-->
<!--        <el-input-->
<!--          v-model="queryParams.usetime"-->
<!--          placeholder="请输入有效期"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="使用时间" prop="usetimestart">-->
<!--        <el-input-->
<!--          v-model="queryParams.usetimestart"-->
<!--          placeholder="请输入使用时间"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="使用时间" prop="usetimeend">-->
<!--        <el-input-->
<!--          v-model="queryParams.usetimeend"-->
<!--          placeholder="请输入使用时间"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="创建时间" prop="createtime">-->
<!--        <el-input-->
<!--          v-model="queryParams.createtime"-->
<!--          placeholder="请输入创建时间"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
<!--      <el-form-item label="删除时间" prop="deletetime">-->
<!--        <el-input-->
<!--          v-model="queryParams.deletetime"-->
<!--          placeholder="请输入删除时间"-->
<!--          clearable-->
<!--          @keyup.enter.native="handleQuery"-->
<!--        />-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          size="mini"-->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          size="mini"-->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          size="mini"-->
<!--          @click="handleExport"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5" style="text-align: right">
        <el-button
          icon="el-icon-delete"
          size="mini"
          @click="handleRecycle"
        >回收站</el-button>
      </el-col>
<!--      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>-->
    </el-row>

    <el-table v-loading="loading" :data="cryptocardList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
<!--      <el-table-column label="ID" align="center" prop="id" />-->
<!--      <el-table-column label="站点" align="center" prop="siteId" />-->
      <el-table-column label="类型" align="center" prop="type" >
        <template slot-scope="scope">
          <span v-if="scope.row.type == 'vip'">VIP套餐</span>
          <span v-if="scope.row.type == 'reseller'">分销商套餐</span>
          <span v-if="scope.row.type == 'usable'">剧场积分套餐</span>
        </template>
      </el-table-column>
      <el-table-column label="套餐" align="center" prop="itemName" />
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="兑换码" align="center" prop="pwd" />
      <el-table-column label="有效期" width="300px" align="center" prop="usetime" />
      <el-table-column label="状态" align="center" prop="status" >
        <template slot-scope="scope">
          <span v-if="scope.row.status == 0">待使用</span>
          <span v-if="scope.row.status == 1">已使用</span>
        </template>
      </el-table-column>
      <el-table-column label="兑换用户" align="center" prop="vsUser.nickname" />
<!--      <el-table-column label="备注" align="center" prop="remark" />-->
<!--      <el-table-column label="有效期" align="center" >-->
<!--        <template slot-scope="scope">-->
<!--          <span>{{ formatDate(scope.row.usetimestart) }}</span>-->
<!--          - -->
<!--          <span>{{ formatDate(scope.row.usetimeend) }}</span>-->
<!--        </template>-->
<!--      </el-table-column>-->
<!--      <el-table-column label="使用时间" align="center" prop="usetimestart" />-->
<!--      <el-table-column label="使用时间" align="center" prop="usetimeend" />-->
<!--      <el-table-column label="创建时间" align="center" prop="createtime" />-->
<!--      <el-table-column label="删除时间" align="center" prop="deletetime" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
<!--          <el-button-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-edit"-->
<!--            @click="handleUpdate(scope.row)"-->
<!--          >修改</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleUpdate(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改卡密对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
<!--        <el-form-item label="站点" prop="siteId">-->
<!--          <el-input v-model="form.siteId" placeholder="请输入站点" />-->
<!--        </el-form-item>-->
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="套餐类型" prop="type">
          <el-radio-group v-model="form.type"  @change="getItemList">
            <el-radio label="vip">VIP套餐</el-radio>
            <el-radio label="reseller">分销商套餐</el-radio>
            <el-radio label="usable">积分套餐</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="套餐" prop="itemId">
          <div v-if="form.type == 'vip'">
            <el-select v-model="form.itemId" placeholder="请选择">
              <el-option
                v-for="item in vipOptions"
                :key="item.id"
                :label="item.title"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div v-else-if="form.type == 'reseller'">
            <el-select v-model="form.itemId" placeholder="请选择">
              <el-option
                v-for="item in resellerOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div v-else-if="form.type == 'usable'">
            <el-select v-model="form.itemId" placeholder="请选择">
              <el-option
                v-for="item in usableOptions"
                :key="item.id"
                :label="item.title"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
          <div v-else>
            <el-select v-model="form.itemId" placeholder="请选择">
              <el-option
                v-for="item in resellerOptions"
                :key="item.key"
                :label="item.value"
                :value="item.key">
              </el-option>
            </el-select>
          </div>
        </el-form-item>
<!--        <el-form-item label="兑换码" prop="pwd">-->
<!--          <el-input v-model="form.pwd" placeholder="请输入兑换码" />-->
<!--        </el-form-item>-->
        <el-form-item label="有效期" prop="usetime">
          <el-date-picker
            v-model="usetimeValue"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            @change="changeUsetime"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="发行总量" prop="issueNum">
          <el-input-number v-model="form.issueNum" controls-position="right" @change="handleIssueNum" :min="1" :precision="0"></el-input-number>
        </el-form-item>
        <el-form-item label="卡密类型" prop="pwdType">
          <el-radio-group v-model="form.pwdType">
            <el-radio label="digitLetter">数字和字母</el-radio>
            <el-radio label="letter">字母</el-radio>
            <el-radio label="digit">数字</el-radio>
            <el-radio label="noZero">无0数字</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="卡密长度" prop="keyLength">
          <el-input-number v-model="form.keyLength" controls-position="right" @change="handleKeyLength" :min="1" :precision="0"></el-input-number>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" placeholder="请输入备注" />
        </el-form-item>
<!--        <el-form-item label="使用时间" prop="usetimestart">-->
<!--          <el-input v-model="form.usetimestart" placeholder="请输入使用时间" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="使用时间" prop="usetimeend">-->
<!--          <el-input v-model="form.usetimeend" placeholder="请输入使用时间" />-->
<!--        </el-form-item>-->
<!--        <el-form-item label="删除时间" prop="deletetime">-->
<!--          <el-input v-model="form.deletetime" placeholder="请输入删除时间" />-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 回收站管理 -->
    <el-dialog title="回收站" :visible.sync="openDel" append-to-body>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            icon="el-icon-refresh-right"
            size="mini"
            :disabled="single"
            @click="handleReduction"
          >还原</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            :disabled="single"
            @click="handleDestruction"
          >销毁</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="success"
            icon="el-icon-refresh-right"
            size="mini"
            @click="batchReduction"
          >还原全部</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            @click="batchDestruction"
          >清空回收站</el-button>
        </el-col>
      </el-row>
      <el-table v-loading="delLoading" :data="delList" stripe @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="ID" align="center" prop="id" />
        <el-table-column label="删除时间" align="center" prop="deletetime" />
        <el-table-column fixed="right" width="150px" label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="clickReduction(scope.row)"
            >还原</el-button>
            <el-button
              size="mini"
              type="text"
              @click="clickDestruction(scope.row)"
            >销毁</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="delTotal>0"
        :total="delTotal"
        :page.sync="delParams.pageNum"
        :limit.sync="delParams.pageSize"
        @pagination="getDelList"
      />
    </el-dialog>
  </div>
</template>

<script>
import { listCryptocard, getCryptocard, delCryptocard, addCryptocard, updateCryptocard } from "@/api/cryptocard/cryptocard";
import { listReseller } from "@/api/reseller/reseller";
import { listUsable } from "@/api/usable/usable";
import { listVip } from "@/api/vip/vip";

export default {
  name: "Cryptocard",
  data() {
    return {
      langList: [],
      dateList: [],
      openDel: false,
      delList: [],
      delLoading: false,
      delTotal: 0,
      delParams: {
        pageNum: 1,
        pageSize: 10,
        deletetime: 1
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 卡密表格数据
      cryptocardList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        siteId: null,
        type: '',
        itemId: null,
        name: null,
        pwd: null,
        usetime: null,
        status: null,
        usetimestart: null,
        usetimeend: null,
        createtime: null,
        deletetime: null
      },
      // 表单参数
      form: {
        type: 'vip',
        pwdType: 'digitLetter'
      },
      // 表单校验
      rules: {
        // siteId: [
        //   { required: true, message: "站点不能为空", trigger: "blur" }
        // ],
        name: [
          { required: true, message: "名称不能为空", trigger: "change" }
        ],
        type: [
          { required: true, message: "类型:vip=VIP套餐,reseller=分销商套餐,usable=剧场积分套餐不能为空", trigger: "change" }
        ],
        // issueNum: [
        //   { required: true, message: "类型:vip=VIP套餐,reseller=分销商套餐,usable=剧场积分套餐不能为空", trigger: "change" }
        // ],
        // status: [
        //   { required: true, message: "状态:0=待使用,1=已使用不能为空", trigger: "change" }
        // ],
        // remark: [
        //   { required: true, message: "备注不能为空", trigger: "blur" }
        // ],
      },
      usetimeValue: [new Date(), new Date()],
      vipOptions:[],
      resellerOptions:[],
      usableOptions:[],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    formatDate(timestamp) {
      const date = new Date(timestamp);
      const year = date.getFullYear();
      const month = this.padZero(date.getMonth() + 1); // 月份从0开始，所以+1
      const day = this.padZero(date.getDate());
      const hours = this.padZero(date.getHours());
      const minutes = this.padZero(date.getMinutes());
      const seconds = this.padZero(date.getSeconds());
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    padZero(num) {
      return num < 10 ? '0' + num : num;
    },
    /** 查询卡密列表 */
    getList() {
      this.loading = true;
      listCryptocard(this.queryParams).then(response => {
        this.cryptocardList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        siteId: null,
        type: null,
        itemId: null,
        name: null,
        pwd: null,
        usetime: null,
        status: null,
        remark: null,
        usetimestart: new Date().getTime(),
        usetimeend: new Date().getTime(),
        createtime: null,
        deletetime: null,
        issueNum: null,
        keyLength: null,
        pwdType: null
      };
      this.usetimeValue = [new Date(), new Date()];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getItemList();
      this.open = true;
      this.title = "添加卡密";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      // const id = row.id || this.ids
      row.deletetime = new Date().getTime();
      updateCryptocard(row).then(response => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateCryptocard(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCryptocard(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除卡密编号为"' + ids + '"的数据项？').then(function() {
        return delCryptocard(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/cryptocard/export', {
        ...this.queryParams
      }, `cryptocard_${new Date().getTime()}.xlsx`)
    },

    /** 隐藏/展示查询列表 */
    handleShow() {
      this.showSearch = !this.showSearch;
    },
    /** 回收站dialog */
    handleRecycle() {
      this.openDel = true;
      this.getDelList();
    },
    /** 查询回收站VIP订单列表 */
    getDelList() {
      this.delLoading = true;
      listCryptocard(this.delParams).then(response => {
        this.delList = response.rows;
        this.delTotal = response.total;
        this.delLoading = false;
      });
    },
    /** 多选还原数据 */
    handleReduction() {
      let num = 0;
      this.ids.forEach(id => {
        let params = {
          id: id,
          deletetime: null
        }
        updateCryptocard(params).then(response => {
        }).catch(e => {
          num++;
        });
      })
      if(num == 0) {
        this.$modal.msgSuccess("还原成功");
        this.getDelList();
      }
    },
    /** 多选销毁数据 */
    handleDestruction() {
      const ids = this.ids;
      this.$modal.confirm('是否确认删除短剧编号为"' + ids + '"的数据项？').then(function() {
        return delCryptocard(ids);
      }).then(() => {
        this.getDelList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 还原全部数据 */
    batchReduction() {
      if(this.delList.length > 0) {
        let num = 0;
        this.delList.forEach(item => {
          item.deletetime = null
          updateCryptocard(item).then(response => {
          }).catch(e => {
            num++;
          });
        })
        if(num == 0) {
          this.$modal.msgSuccess("还原成功");
          this.getDelList();
        }
      } else {
        this.$modal.msgWarning("回收站暂无数据");
      }
    },
    /** 销毁全部数据 */
    batchDestruction() {
      if(this.delList.length > 0) {
        const ids = this.delList.map(obj => obj.id);
        this.$modal.confirm('是否确认删除回收站中的全部数据？').then(function() {
          return delCryptocard(ids);
        }).then(() => {
          this.getDelList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      } else {
        this.$modal.msgWarning("回收站已经是空的了");
      }
    },
    /** 行间单击还原数据 */
    clickReduction(row) {
      row.deletetime = null
      updateCryptocard(row).then(response => {
        this.$modal.msgSuccess("还原成功");
        this.getDelList()
      });
    },
    /** 行间单击销毁数据 */
    clickDestruction(row) {
      const ids = [];
      ids.push(row.id)
      this.$modal.confirm('是否确认删除短剧编号为"' + ids + '"的数据项？').then(function() {
        return delCryptocard(ids);
      }).then(() => {
        this.getDelList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    changeUsetime() {
      let begin = this.usetimeValue[0];
      let end = this.usetimeValue[1];
      let usetime = this.formatDate(begin) + "-" + this.formatDate(end);
      this.form.usetime = usetime;
      this.form.usetimestart = new Date(begin).getTime();
      this.form.usetimeend = new Date(end).getTime();
    },
    handleIssueNum(value) {
      this.form.issueNum = value
    },
    handleKeyLength(value) {
      this.form.keyLength = value
    },
    getItemList() {
      let params = {
        pageNum: 1,
        pageSize: 99999
      }
      if (this.form.type == 'vip') {
        listVip(params).then(response => {
          this.vipOptions = response.rows;
        });
      } else if (this.form.type == 'reseller') {
        listReseller(params).then(response => {
          this.resellerOptions = response.rows;
        });
      } else if (this.form.type == 'usable') {
        listUsable(params).then(response => {
          this.usableOptions = response.rows;
        });
      }
    }
  }
};
</script>
